/**
 * @author  guocailee
 */
import Vue from 'vue'
import md5 from 'js-md5'
import * as loginInfoUtil from '../utils/loginInfo'

/**
 * 用户登录
 * @param  {[type]} account [description]
 * @return {[type]}         [description]
 */
export const userLogin = (account) => {
  return new Promise((resolve, reject) => {
    let mdpwd = md5(account.password)
    Vue.fetch.post('account/login', {
      username: account.username,
      password: mdpwd
    }).then(data => {
      if (data.body.code === '00000000') {
        let loginInfo = data.body.payload.results
        loginInfo.sessionId = data.body.sessionId
        loginInfoUtil.saveInfo(loginInfo)
        resolve(loginInfo)
      } else {
        reject(data.body.message)
      }
    }).catch(data => {
      reject(data)
    })
  })
}

/**
 * 用户登出
 * @return {[Promise]}         [API call results]
 */
export const userLogout = () => {
  return new Promise((resolve, reject) => {
    Vue.fetch.post('account/logout', {}).then(data => {
      if (data.body.code === '00000000') {
        loginInfoUtil.removeInfo()
        resolve()
      } else {
        reject(data.body.message)
      }
    }).catch(data => {
      reject(data)
    })
  })
}

export const userRegister = (account) => {
  return new Promise((resolve, reject) => {
    Vue.fetch.post('account/register', {
      username: account.username,
      password: md5(account.password)
    }).then((data) => {
      if (data.body.code === '00000000') {
        resolve()
      } else {
        reject(data.body.message)
      }
    }).catch(data => {
      reject(data)
    })
  })
}

export const getUserInfoforget = (username) => {
  return new Promise((resolve, reject) => {
    Vue.fetch.post('account/queryuserinfoforget', {
      username: username
    }).then((data) => {
      if (data.body.code === '00000000') {
        resolve(data.body.payload.results)
      } else {
        reject(data.body.message)
      }
    }).catch(data => {
      reject(data)
    })
  })
}
